package org.example.book.service;

import org.example.book.dutychain.AbstractBusinessHandler;
import org.example.book.dutychain.CityHandler;
import org.example.book.pojo.BusinessLaunch;
import org.example.book.pojo.UserInfo;
import org.example.book.repo.BusinessLaunchRepository;
import org.example.book.repo.UserRepository;
import org.example.book.util.HandlerEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserServcie {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BusinessLaunchRepository businessLaunchRepository;

    @Value("${duty.chain}")
    private String handlerType;

    // 记录当前handlerType的配置，判断duty.chain是否有修改
    private String currentHandlerType;
    // 记录当前的责任链头节点，如果配置没有修改，下次直接返回
    private AbstractBusinessHandler currentHandler;

    public List<BusinessLaunch> filterBusinessLaunch(String city, String sex, String product) {
        List<BusinessLaunch> launchList = businessLaunchRepository.findAll();
        return buildChain().processHandler(launchList, city, sex, product);
    }

    public String login(String account, String password) {
        UserInfo userInfo = userRepository.findByUserNameAndUserPassword(account, password);
        if (userInfo == null) {
            return "account /  password Error";
        }
        return "login success";
    }

    public String register(UserInfo userInfo) {
        if (checkUserExists(userInfo.getUserName())) {
            throw new RuntimeException("user already exists");
        }
        userInfo.setCreateDate(new Date());
        userRepository.save(userInfo);
        return "register success";
    }

    public boolean checkUserExists(String username) {
        UserInfo byUserName = userRepository.findByUserName(username);
        return byUserName != null;
    }

    /**
     * 组装责任链并返回责任链首节点
     *
     * @return
     */
    private AbstractBusinessHandler buildChain() {
        // 如果没有配置，直接返回null
        if (handlerType == null) {
            return null;
        }
        // 如果第一次配置，记录下来
        if (currentHandler == null) {
            this.currentHandlerType = this.handlerType;
        }
        if (this.handlerType.equals(currentHandlerType) && this.currentHandler != null) {
            return this.currentHandler;
        } else {
            System.out.println("配置有修改或者初始化，组装责任链");
            synchronized (this) {
                try {
                    // 创建一个哑节点
                    AbstractBusinessHandler dummyHeadHandler = new CityHandler();
                    AbstractBusinessHandler preHandler = dummyHeadHandler;
                    List<String> handlerTypeList = Arrays.asList(handlerType.split(","));
                    for (String handlerType : handlerTypeList) {
                        AbstractBusinessHandler handler = (AbstractBusinessHandler) Class.forName(HandlerEnum.valueOf(handlerType).getValue()).newInstance();
                        preHandler.nextHandler = handler;
                        preHandler = handler;
                    }
                    this.currentHandler = dummyHeadHandler.nextHandler;
                    this.currentHandlerType = this.handlerType;
                    return this.currentHandler;
                } catch (Exception e) {
                    throw new UnsupportedOperationException(e);
                }
            }
        }
    }
}
